<template>
	<view>
		<view class="card u-p-l-20 u-p-t-24 u-p-r-20 u-p-b-32" v-if="type=='0'">

			<view class="flex align-center justify-center">
				<view :class="orderInType==1?'cur':''" class="u-font-36 text-black text-center " style="width: 50%;"
					@click="handleOrderInType(1)">
					快递配送</view>
				<view :class="orderInType==2?'cur':''" class="u-font-36 text-black text-center" style="width: 50%;"
					@click="handleOrderInType(2)">门店自取
				</view>
			</view>
			<view class="u-m-t-40 flex align-center justify-between" v-if="type=='0'&&orderInType==2">
				<view v-if="!stageInfo.housingName" @click="$u.route('/pages/index/stage/stage')" style="width: 100%;"
					class="flex align-center justify-between">
					<view style="color: #999;" class="u-font-30 text-black">
						选择服务门店</view>
					<u-icon name="arrow-right" size="10" color="#999"></u-icon>
				</view>
				<view v-else @click="$u.route('/pages/index/stage/stage')">
					<view>
						<view class="u-font-32 text-black">{{stageInfo.housingName}}（{{stageInfo.companyLianxiPhone}}）
						</view>
						<view class="u-m-t-16 u-font-24 text999">{{stageInfo.equAddress}}
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="card u-p-l-20 u-p-t-24 u-p-r-20 u-p-b-24">
			<view v-if="addressInfoList.length>0" @click="$u.route('/pages/personal/address/address?isBack=1')">
				<view>
					<view class="u-font-32 text-black">{{addressInfo.name}}（{{addressInfo.phone}}）</view>
					<view class="u-m-t-16 u-font-24 text999">{{addressInfo.area}}({{addressInfo.detailsAddress}})
					</view>
				</view>

			</view>
			<view v-else class="flex align-center justify-between">
				<view class="u-font-30 text-black" style="color:#999"
					@click="$u.route('/pages/personal/address/address?isBack=1')">
					添加地址</view>
				<u-icon name="arrow-right" size="10" color="#999"></u-icon>
			</view>
		</view>
		<view class="card u-p-l-20 u-p-r-20 u-p-t-24 u-p-b-24" v-if="orderInType=='1'&&type=='0'">
			<view class="u-m-t-10 flex align-center justify-between" @click="handleShowGetTime()">
				<view style="color: #999;" class="u-font-30 text-black" v-if="!changeShowTimes">
					选择上门时间</view>
				<text style="color: gray;" class="u-font-26" v-else>{{changeShowTimes}}</text>
				<u-icon name="arrow-right" size="10" color="#999"></u-icon>
			</view>
		</view>
		<view class="card u-p-l-20 u-p-r-20 u-p-t-24 u-p-b-24" v-for="(item,k) in cartInfoList" :key="k">
			<view class="flex">
				<view class="img-box">
					<u-image :showLoading="true" mode="aspectFill" radius="8rpx" :src="item.image" width="174rpx"
						height="174rpx">
						<view slot="loading">
							<u-loading-icon></u-loading-icon>
						</view>
					</u-image>
				</view>
				<view class="u-m-l-10" style="width: 100%;">
					<view class="ellipsis2 text-black">{{item.productName}}</view>
					<view class="u-m-t-10 u-font-xs text999">{{item.unit}}</view>
					<view class="u-m-t-10 flex align-center justify-between" style="width: 100%;">
						<view style="color: #FD002B;">
							<text class="text-bold  u-font-xs">￥</text>
							<text
								class="u-font-lgm  text-bold u-m-r-16">{{parseFloat(item.salePrice).toFixed(2)}}</text>
							<text class="u-font-xs" style="color: #999;">原价：</text>
							<text class="u-font-xs"
								style="color: #999;text-decoration: line-through;">{{parseFloat(item.price).toFixed(2)}}</text>
						</view>
						<view class="u-font-xs text999"><!-- x{{item.count}} -->
							<u-number-box v-model="item.count" buttonSize="25"
								@change="(value)=>handleUpdateProductToShoppingCar(item,value)"></u-number-box>
						</view>
					</view>
				</view>
			</view>

			<view class="u-m-t-40 flex align-center justify-between">
				<view>商品总额</view>
				<view class="text-black text-bold">
					<text class="u-font-24">￥</text>
					<text>{{parseFloat(item.amount).toFixed(2)}}</text>
				</view>
			</view>
		</view>
		<view class="card u-p-l-20 u-p-r-20 u-p-t-24 u-p-b-24" v-if="type=='0'">
			<view class="u-m-t-10 flex align-center justify-between">
				<view>优惠券</view>
				<view class="flex align-center" @click="handleToCouponInfo()" v-if="!isUseCoupon">
					<text class="u-font-24 text999" v-if="userCouponInfoCount==0">暂无可用</text>
					<text class="u-font-24 text999" v-else>{{userCouponInfoCount}}张可用</text>
					<u-icon name="arrow-right" size="14rpx"></u-icon>
				</view>
				<view class="flex align-center" @click="handleToCouponInfo()" v-if="isUseCoupon">
					<text
						class="u-font-24 text-red">-{{parseFloat(userCouponInfo.couponInfo.amount).toFixed(2)}}&nbsp;元</text>
					<u-icon name="arrow-right" size="14rpx"></u-icon>
				</view>
			</view>
		</view>
		<view @click="open" class="card u-p-l-20 u-p-r-20 u-p-t-26 u-p-b-26 flex align-center" v-if="type=='0'">
			<u-icon name="/static/index/o-bj.png" size="68rpx"></u-icon>
			<view class="u-m-l-12">
				<view class="text-black">保价</view>
				<view class="u-font-24 text999">贵重物品建议保价</view>
			</view>
		</view>
		<view class="card u-p-l-20 u-p-t-24 u-p-b-24">
			<view class="u-font-36 text-black text-bold">备注</view>
			<view class="flex align-center flex-wrap" v-if="type=='0'">
				<view class="u-m-t-24 u-m-r-32 tag" v-for="(item,i) in orderRemarkList" :key="i"
					@click="handleCheckRemark(item.dictValue)">{{item.dictValue}}
				</view>
			</view>
			<view class="u-m-t-24 u-m-r-24">
				<u--textarea v-model="remark" class="textarea" placeholder="请输入内容"></u--textarea>
			</view>
		</view>

		<view style="height: 210rpx;"></view>

		<view class="footer">
			<view class="u-p-t-20 u-p-t-20  flex align-center justify-between">
				<view>
					<view>
						<text class="text-black">总计:</text>
						<text class="u-font-24" style="color: #FD002B;">￥</text>
						<text class="u-font-32 text-bold"
							style="color: #FD002B;">{{parseFloat(sumAmount).toFixed(2)}}</text>
					</view>
				</view>
				<view class="btn" @click="handleToSumbitOrder()">立即支付</view>
			</view>
		</view>

		<insured ref="insured" @getForm="getForm"></insured>

		<!-- <u-modal show="false" title="温馨提示" @cancel="show=false" @confirm="$u.route('/pages/personal/address/address')"
			:showCancelButton="true" confirmText="去填写地址">
			<view slot="default" style="color: #999;">您还没有地址，立即填写地址！</view>
		</u-modal> -->

		<!-- 预约时间 -->
		<view @touchmove.stop.prevent="stopPent">
			<u-popup :show="popupshow" :closeable="true" @close="popupshow=false">
				<view class="popup u-p-32">
					<view class="">请选择上门时间</view>
					<view class="flex">
						<view class="nav">
							<view v-if="toDaysTimes.length>0" @click="selectDay('toDay',dayParams.yesterday1)"
								:class="dayParams.yesterday1==dayCur?'active':''" class="tab">今天
								({{dayParams.yesterday1}})
							</view>
							<view @click="selectDay('tomorrow',dayParams.yesterday2)"
								:class="dayParams.yesterday2==dayCur?'active':''" class="tab">明天
								({{dayParams.yesterday2}})
							</view>
							<view @click="selectDay('acquired',dayParams.yesterday3)"
								:class="dayParams.yesterday3==dayCur?'active':''" class="tab">
								后天({{dayParams.yesterday3}})
							</view>
						</view>
						<view class="time-box ">
							<scroll-view class="slide" :scroll-y="true">
								<block v-for="(it,k) in timeArr" :key="k">
									<view @click="selectTime(it,k)" :class="timeCur==k?'active':''" class="time">{{it}}
									</view>
								</block>
							</scroll-view>
						</view>
					</view>
					<u-button type="primary" color="#FF5B00" @click="popupshow=false">确认上门时间</u-button>
				</view>
			</u-popup>
		</view>


	</view>
</template>

<script>
	const dayjs = require("dayjs");
	import insured from '@/components/x-unit/insured/insured'
	import {
		getUserAddressInfo,
		getShoppingCarListByIds,
		getUserCouponInfoList,
		getUserCouponInfo,
		submitOrder,
		getDictList,
		payOrder,
		getOrderToHomeTime,
		getCompanyInfo,
		updateProductToShoppingCar
	} from '@/common/api/api.js'
	export default {
		components: {
			insured
		},
		data() {
			return {
				dayParams: {
					yesterday1: '',
					yesterday2: '',
					yesterday3: '',
				},
				dayCur: '',
				timeCur: 0,
				timeArr: [],
				popupshow: false,
				show: false,
				value: '1',
				value1: '',
				userInfoId: '',
				addressInfo: undefined, // 地址信息
				addressInfoList: [], // 地址列表
				// posthouseInfo: '', // 驿站信息
				couponInfo: "", // 优惠券信息
				xihuXieYiInfo: "", // 洗护服务协议
				sanFangXieYiInfo: "", // 三方协议
				ids: "", //选中的购物产品ID
				cartInfoList: [],
				sumAmount: 0.00,
				userCouponInfoCount: 0,
				type: "0",
				isUseCoupon: false,
				useCouponId: "",
				userCouponInfo: {},
				orderRemarkList: [], // 订单备注字典,
				orderInType: 1, // 是否上门
				isInsure: 1, // 是否保价 1 不保价 2 保价
				insurePrice: 0.00, //保价金额
				declarePrice: 0.00, // 物品价格
				stageInfo: undefined, // 驿站地址
				remark: '', // 备注
				isTiJiao: 0,
				companyId: '',
				visitBeginTime: undefined, // 上门开始时间 如果是洗护订单 必填
				visitEndTime: undefined, // 上门结束时间 如果是洗护订单 必填
				days: {}, // 时间段
				toDaysTimes: [], // 今天时间
				tomorrowTimes: [], // 明天时间
				acquiredTimes: [], // 后天时间,
				changeShowTimes: undefined,
				day: "",
				companyInfo: {},

			}
		},
		onLoad(options) {
			// 获取购物车传过来的数据
			if (options.idsArr) {
				this.ids = options.idsArr;
			}
			this.handleGetUserAddressInfo();
			this.handleGetShoppingCarListByIds(this.ids);
			this.handleGetDictList();
			this.handleGetOrderToHomeTime();


		},
		mounted() {
			// 监听返回事件并刷新页面
			uni.$on('back', this.onNavigateTo);
			// 监听选择驿站
			uni.$on("stageBack", this.onNavigateToStageBack);
			// 监听地址
			uni.$on("addressBack", this.onNavigateToAddressBack);
		},
		beforeDestroy() {
			// 移除返回事件
			uni.$off('back', this.onNavigateTo);
			// 移除返回事件
			uni.$off('stageBack', this.onNavigateToStageBack);
			// 移除返回事件
			uni.$off('addressBack', this.onNavigateToAddressBack);
		},
		methods: {
			handleUpdateProductToShoppingCar(item, e) {
				console.log("item.count", item, e);
				var params = {
					id: item.id,
					count: e.value,
					salePrice: item.salePrice
				}
				updateProductToShoppingCar(params).then(res => {
					this.handleGetShoppingCarListByIds(this.ids);
				})
			},
			stopPent() {
				return;
			},
			//获取公司信息
			handleGetCompanyInfo() {
				getCompanyInfo({
					companyId: '338c7c05c245490c8a5a648382afb53e'
				}).then(res => {
					this.companyInfo = res.data;
				})
			},
			// 上门时间
			handleShowGetTime() {
				this.popupshow = true;
			},

			//日期
			selectDay(day, days) {
				this.dayCur = days;
				this.day = day;
				if (this.day == 'toDay') {
					this.timeArr = this.toDaysTimes;
				}
				if (this.day == 'tomorrow') {
					this.timeArr = this.tomorrowTimes;
				}
				if (this.day == 'acquired') {
					this.timeArr = this.acquiredTimes;
				}
				let clickTimes=this.timeArr[0];
				this.visitBeginTime = clickTimes[0];
				this.visitEndTime = clickTimes[1];
				
			},
			//时间
			selectTime(times, index) {
				this.timeCur = index;
				let clickTimes = times.split('-');

				if (this.day == 'toDay') {
					this.timeArr = this.toDaysTimes;
					this.changeShowTimes = "今天 "
				}
				if (this.day == 'tomorrow') {
					this.timeArr = this.tomorrowTimes;
					this.changeShowTimes = "明天 "
				}
				if (this.day == 'acquired') {
					this.timeArr = this.acquiredTimes;
					this.changeShowTimes = "后天 "
				}
				this.changeShowTimes = this.changeShowTimes + this.dayCur;
				this.changeShowTimes = this.changeShowTimes + "(" + times + ")";
				this.visitBeginTime = clickTimes[0];
				this.visitEndTime = clickTimes[1];
			},
			//获取保价参数
			getForm(e) {
				this.insurePrice = e.insurePrice;
				this.declarePrice = e.price;
				if (this.insurePrice > 0) {
					this.isInsure = 2; // 保价
				} else {
					this.isInsure = 1; // 不保价
				}
			},
			// 监听驿站返回调用函数
			onNavigateToStageBack(item) {
				console.log(item);
				this.stageInfo = item;
			},
			// 监听地址回调
			onNavigateToAddressBack(item) {
				console.log(item)
				this.addressInfo = item;
				this.addressInfoList.push(item);
			},
			//选择优惠券
			onNavigateTo(id) {
				// 读取传递的数据并刷新页面
				console.log('传递的数据', id);
				if (id) {
					this.isUseCoupon = true;
					this.useUserCouponId = id;
					getUserCouponInfo({
						id: id
					}).then(res => {
						this.userCouponInfo = res.data;
						this.sumAmount = this.$utils.numberSub(this.sumAmount, res.data.couponInfo.amount);
					})
				}
			},
			open() {
				this.$refs.insured.show = true;
			},
			// 获取上门时间
			handleGetOrderToHomeTime() {
				getOrderToHomeTime().then(res => {
					this.dayParams.yesterday1 = res.data.days.toDay;
					this.dayParams.yesterday2 = res.data.days.tomorrow;
					this.dayParams.yesterday3 = res.data.days.acquired;
					this.dayCur = this.dayParams.yesterday1;
					this.timeArr = res.data.toDaysTimes;
					this.toDaysTimes = res.data.toDaysTimes;
					this.tomorrowTimes = res.data.tomorrowTimes;
					this.acquiredTimes = res.data.acquiredTimes;
					if (this.toDaysTimes.length == 0) {
						this.timeArr = this.tomorrowTimes;
						this.dayCur = this.dayParams.yesterday2;
						this.day = "tomorrow";
					} else {
						this.day = "toDay";
					}
					let clickTimes=this.timeArr[0];
					this.visitBeginTime = clickTimes[0];
					this.visitEndTime = clickTimes[1];
					

				})
			},
			// 获取用户默认地址
			handleGetUserAddressInfo() {
				this.userInfoId = this.$store.state.$token;
				getUserAddressInfo({
					userInfoId: this.userInfoId,
					status: "1"
				}).then(res => {
					if (res.data.list.length > 0) {
						this.addressInfo = res.data.list[0];

					} else {
						this.show = true;
					}
					this.addressInfoList = res.data.list;

				})
			},
			// 根据选中购物车的商品查询具体商品信息
			handleGetShoppingCarListByIds(ids) {
				this.sumAmount = 0.00;
				getShoppingCarListByIds({
					ids: ids
				}).then(res => {
					this.cartInfoList = res.data.map(item => {
						this.sumAmount = this.$utils.numberAdd(this.sumAmount, item.amount);
						this.type = item.type;
						this.companyId = item.companyId;
						return item;
					});
					this.handleGetUserCouponInfoList(this.sumAmount);
				})
			},
			// 获取用户未使用的优惠券信息
			handleGetUserCouponInfoList(orderAmount) {
				var params = {
					userInfoId: this.$store.state.$token,
					status: "0",
					type: this.type,
					fullSub: orderAmount
				};
				getUserCouponInfoList(params).then(res => {
					this.userCouponInfoCount = res.data.total;
				})
			},
			// 跳转优惠券页面
			handleToCouponInfo() {
				this.$u.route('/pages/index/coupon/coupon?type=' + this.type + '&fullSub=' + this.sumAmount);
			},
			// 提交订单
			handleToSumbitOrder() {
				if (this.isTiJiao == 0) {
					if (this.type == '0') {
						if (this.orderInType == 1) {
							if (!this.stageInfo) {
								this.stageInfo = {
									companyId: "338c7c05c245490c8a5a648382afb53e",
									companyLianxiPhone: this.companyInfo.companyLianxiPhone,
									equXinghao: '禾汇知味总店',
								}
							}
							
						} else {
							if (!this.stageInfo) {
								uni.$u.toast('请选择附近门店');
								return;
							}
						}
						if (!this.addressInfo) {
							uni.$u.toast('请填写地址');
							return;
						}
					} else {
						if (!this.addressInfo) {
							uni.$u.toast('请填写地址');
							return;
						}

					}


					this.show = true;
					var params = {
						cartsIds: this.ids,
						voucherId: this.useUserCouponId,
						orderType: this.type,
						userInfoId: this.userInfoId,
						lianxiName: this.addressInfo.name,
						phone: this.addressInfo.phone,
						roomAddress: (this.addressInfo.area +
							this.addressInfo.detailsAddress),
						orderInType: this.orderInType,
						isInsure: this.isInsure,
						insurePrice: this.insurePrice,
						declarePrice: this.declarePrice,
						remark: this.remark,
						companyId: this.type == '0' ? this.stageInfo.companyId : this.companyId,
						visitBeginTime: this.visitBeginTime,
						visitEndTime: this.visitEndTime,
						day: this.day
					}
					uni.showLoading({
						title: "创建订单中..."
					})
					console.log("params",params);
					submitOrder(params).then(res => {
						if (res.code == 200) {
							this.handlePayOrder(res.data);
							this.isTiJiao = 1;
						}
						uni.hideLoading();
					})
				}

			},
			// 订单备注字典
			handleGetDictList() {
				getDictList({
					type: "order_remark"
				}).then(res => {
					this.orderRemarkList = res.data;
				})
			},
			// 选择备注
			handleCheckRemark(item) {
				this.remark = item + " " + this.remark;
			},
			// 更改订单是否上门
			handleOrderInType(t) {
				this.orderInType = t;
			},
			handlePayOrder(orderId) {
				const that = this;
				payOrder({
					id: orderId
				}).then(res => {
					if (res.code == 200) {
						uni.requestPayment({
							provider: "payment",
							timeStamp: res.data.timeStamp,
							nonceStr: res.data.nonceStr,
							package: res.data.packageVal,
							signType: res.data.signType,
							paySign: res.data.paySign,
							success: function(res) {
								console.log('success:' + JSON.stringify(res));
								that.isTiJiao = 0;
								uni.reLaunch({
									url: '/pages/order/order'
								})
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
								that.isTiJiao = 0;
								uni.reLaunch({
									url: '/pages/order/order'
								})
							}
						})
					}
				})
			}

		}
	}
</script>

<style lang="scss">
	.card {
		margin-top: 20rpx;
		margin-left: 32rpx;
		margin-right: 32rpx;
		width: 686rpx;
		min-height: 100rpx;
		background: #FFFFFF;
		border-radius: 8rpx;
	}

	.tag {
		min-width: 184rpx;
		height: 56rpx;
		line-height: 56rpx;
		padding: 0 10rpx;
		text-align: center;
		background: #F7F9FC;
		border-radius: 28rpx 28rpx 28rpx 28rpx;
		font-size: 26rpx;
		color: #333333;
	}

	.textarea {
		width: 646rpx;
		height: 240rpx;
		background: #F7F9FC;
		border-radius: 8rpx;
	}

	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #FFFFFF;
		padding: 24rpx 32rpx;
		z-index: 999;

		.btn {
			width: 320rpx;
			height: 84rpx;
			line-height: 84rpx;
			text-align: center;
			background: #FF5B00;
			border-radius: 8rpx;
			color: #FFFFFF;
		}
	}

	.cur {
		color: #FF5B00;
	}

	.popup {
		height: 800rpx;

		.slide {
			height: 600rpx;
			// overflow-y: scroll;
		}

		.nav {
			width: 360rpx;
			margin-top: 20rpx;

			.tab {
				text-align: center;
				padding: 16rpx 10rpx;
			}

			.active {
				background-color: #f0f0f0;
				color: #72bfb6;
			}
		}

		.time-box {
			width: 100%;
			text-align: center;
			margin-bottom: 32rpx;

			.time {
				padding-top: 20rpx;
				padding-bottom: 20rpx;
			}

			.active {
				color: #72bfb6;
			}
		}
	}
</style>